package cn.butcher21.controller.timeline;


import cn.butcher21.utils.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * butcher create in 2021/03/07/13:25,
 * <p>
 * 处理新增时间线，向数据库中插入数据
 */
@WebServlet("/insertTimeLine")
public class InsertTimeLine extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取时间与内容
        String time = req.getParameter("time");
        String content = req.getParameter("content");
        String pic = req.getParameter("pic");
        DButil dButil = new DButil();

//        插入数据之前先进行查询，如果数据库中存在当天的事件，则更新，否则插入
        PreparedStatement ps = dButil.getPs("select time from yt_timeline where time=?");

        try {
            ps.setString(1, time);
            ResultSet rs = dButil.getRs(ps.executeQuery());
            if (rs.next()) {
//                说明存在此条数据了，执行更新操作
                ps = dButil.getPs("UPDATE yt_timeline SET content=?,pic=?WHERE time=?");
                ps.setString(1, content);
                ps.setString(2, pic);
                ps.setString(3, time);
                ps.executeUpdate();
            } else {
//                说明不存在，进行插入
                ps = dButil.getPs("insert into yt_timeline(time,content,pic) values(?,?,?)");
                ps.setString(1, time);
                ps.setString(2, content);
                ps.setString(3, pic);
                ps.execute();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dButil.closeAll();
        }

    }
}
